
import Toast from 'tdesign-miniprogram/toast/index';
import Dialog from 'tdesign-miniprogram/dialog/index';
import { submitRoomOrder } from '../../services/api';

Page({
  data: {
    cartData: [], // 购物车商品列表
    totalAmount: 0, // 总金额
    swipeRight: [{ text: '删除', className: 'delete-btn' }], // 左滑删除按钮
  },

  onShow() {
    this.loadCartData();
    this.getTabBar().init();
  },

  loadCartData() {
    const cartData = wx.getStorageSync('cartData') || [];
    this.setData({ cartData });
    this.calculateTotal();
  },

  calculateTotal() {
    const total = this.data.cartData.reduce((sum, item) => {
      return sum + parseFloat(item.price) * item.quantity;
    }, 0);
    this.setData({
      totalAmount: total.toFixed(2),
    });
  },

  onQuantityChange(e) {
    const { item } = e.currentTarget.dataset;
    const newQuantity = e.detail.value;
    const index = this.data.cartData.findIndex((cartItem) => cartItem.id === item.id);

    if (index > -1) {
      this.setData({
        [`cartData[${index}].quantity`]: newQuantity,
      });
      this.saveCartData();
      this.calculateTotal();
    }
  },

  onSwipeCellClick(e) {
    const { item } = e.currentTarget.dataset;
    this.deleteItem(item.id);
  },

  deleteItem(itemId) {
    const newCartData = this.data.cartData.filter((cartItem) => cartItem.id !== itemId);
    this.setData({ cartData: newCartData });
    this.saveCartData();
    this.calculateTotal();
    Toast({
      context: this,
      selector: '#t-toast',
      message: '已删除',
    });
  },

  onClearCart() {
    if (this.data.cartData.length === 0) return;
    Dialog.confirm({
      title: '确认清空',
      content: '确定要清空购物车中的所有商品吗？',
      confirmBtn: '清空',
      cancelBtn: '取消',
    }).then(() => {
      this.setData({ cartData: [], totalAmount: 0 });
      this.saveCartData();
    });
  },

  saveCartData() {
    wx.setStorageSync('cartData', this.data.cartData);
  },

  onSubmitOrder() {
    if (this.data.cartData.length === 0) return;
    const roomId = getApp().globalData.roomId || 'DEV_TEST'; // 获取包厢号，如果没有则使用开发测试值

    /* 开发时临时注释掉，方便测试
    if (!roomId) {
      Dialog.alert({ title: '下单失败', content: '无法获取包厢号，请通过扫码重新进入小程序。' });
      return;
    }
    */
    
    Dialog.confirm({
      title: '确认下单',
      content: `将为包厢 ${roomId} 下单，商品将记入房账。`,
      confirmBtn: '确定',
      cancelBtn: '取消',
    }).then(() => {
      const orderData = {
        roomId: roomId,
        items: this.data.cartData,
        totalAmount: this.data.totalAmount, // 传递“分”单位的总金额
      };

      submitRoomOrder(orderData).then(res => {
        if (res.success) {
          this.setData({ cartData: [], totalAmount: 0 });
          this.saveCartData();

          Toast({
            context: this,
            selector: '#t-toast',
            message: '下单成功！',
            icon: 'check-circle',
          });
          
          setTimeout(() => {
            wx.navigateTo({ url: '/pages/order/order-list/index' });
          }, 1500);
        } else {
          throw new Error('提交订单失败');
        }
      }).catch(err => {
        console.error('下单API调用失败:', err);
        Dialog.alert({ title: '下单失败', content: `服务开小差了，请稍后重试。(${err.message})` });
      });
    }).catch(() => {
      // 用户点击取消，不做任何事
    });
  },

  onGoToHome() {
    wx.switchTab({ url: '/pages/home/home' });
  },
});
